
package com.jf.cloud.im.service.impl;

import cn.hutool.core.date.DateUtil;
import com.jf.cloud.api.auth.bo.UserInfoInTokenBO;
import com.jf.cloud.api.multishop.bo.EsShopDetailBO;
import com.jf.cloud.api.multishop.feign.ShopUserFeignClient;
import com.jf.cloud.api.multishop.vo.ShopUserVO;
import com.jf.cloud.api.platform.feign.SysUserClient;
import com.jf.cloud.api.platform.vo.SysUserVO;
import com.jf.cloud.api.user.vo.UserApiVO;
import com.jf.cloud.common.database.dto.PageDTO;
import com.jf.cloud.common.database.util.PageUtil;
import com.jf.cloud.common.database.vo.PageVO;
import com.jf.cloud.common.exception.LuckException;
import com.jf.cloud.common.response.ServerResponseEntity;
import com.jf.cloud.im.constants.*;
import com.jf.cloud.im.mapper.ImMsgBizUserHistoryMapper;
import com.jf.cloud.im.model.ImMsgBizEmployeeRecent;
import com.jf.cloud.im.model.ImMsgBizUser;
import com.jf.cloud.im.model.ImMsgBizUserHistory;
import com.jf.cloud.im.service.ImMsgBizEmployeeRecentService;
import com.jf.cloud.im.service.ImMsgBizUserHistoryService;
import com.jf.cloud.im.service.ImMsgBizUserService;
import com.jf.cloud.im.vo.MessageInfoVO;
import com.jf.cloud.im.vo.MsgItemVO;
import ma.glasnost.orika.MapperFacade;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 店铺和用户历史聊天记录表
 *
 * @author zz
 * @date 2021-08-25 13:58:56
 */
@Service
public class ImMsgBizUserHistoryServiceImpl implements ImMsgBizUserHistoryService {

    @Autowired
    private ImMsgBizUserHistoryMapper imMsgBizUserHistoryMapper;

    @Autowired
    private ImMsgBizUserService imMsgBizUserService;

    @Autowired
    private ImMsgBizEmployeeRecentService imMsgBizEmployeeRecentService;

    @Autowired
    private SysUserClient sysUserClient;

    @Autowired
    private ShopUserFeignClient shopUserFeignClient;
    @Autowired
    private MapperFacade mapperFacade;

    @Override
    public PageVO<ImMsgBizUserHistory> page(PageDTO pageDTO) {
        return PageUtil.doPage(pageDTO, () -> imMsgBizUserHistoryMapper.list());
    }

    @Override
    public PageVO<ImMsgBizUserHistory> pageBySendTypeBizIdUserId(PageDTO pageDTO, Integer sendType, Long bizId, Long employeeId, Long userId) {
        PageVO<ImMsgBizUserHistory> page = PageUtil.doPage(pageDTO, () -> imMsgBizUserHistoryMapper.listBySendTypeBizIdUserId(sendType, bizId, employeeId, userId));
        List<Long> employeeIds = page.getList().stream().map(ImMsgBizUserHistory::getEmployeeId).collect(Collectors.toList());
        Map<Long, String> nickNameMap;
        // 查询平台的客服昵称
        if (Objects.equals(sendType, SendType.PLATFORM)) {
            ServerResponseEntity<List<SysUserVO>> sysUserResponseEntity = sysUserClient.getImSysUserList(employeeIds);
            if (!sysUserResponseEntity.isSuccess()) {
                throw new LuckException(sysUserResponseEntity.getMsg());
            }
            List<SysUserVO> sysUserList = sysUserResponseEntity.getData();
            nickNameMap = sysUserList.stream().collect(Collectors.toMap(SysUserVO::getSysUserId, SysUserVO::getNickName));
        } else if (Objects.equals(sendType, SendType.SHOP)) {
            ServerResponseEntity<List<ShopUserVO>> shopUserResponseEntity = shopUserFeignClient.getImShopUserList(employeeIds);
            if (!shopUserResponseEntity.isSuccess()) {
                throw new LuckException(shopUserResponseEntity.getMsg());
            }
            List<ShopUserVO> sysUserList = shopUserResponseEntity.getData();
            nickNameMap = sysUserList.stream().collect(Collectors.toMap(ShopUserVO::getShopUserId, ShopUserVO::getNickName));
        } else {
            nickNameMap = new HashMap<>();
        }
        for (ImMsgBizUserHistory imMsgBizUserHistory : page.getList()) {
            if (!nickNameMap.containsKey(imMsgBizUserHistory.getEmployeeId())) {
                continue;
            }
            imMsgBizUserHistory.setNickName(nickNameMap.get(imMsgBizUserHistory.getEmployeeId()));
        }
        return page;
    }

    @Override
    public ImMsgBizUserHistory getById(Long id) {
        return imMsgBizUserHistoryMapper.getById(id);
    }

    @Override
    public ImMsgBizUserHistory getByParam(ImMsgBizUserHistory imMsgBizUserHistory) {
        return imMsgBizUserHistoryMapper.getByParam(imMsgBizUserHistory);
    }

    @Override
    public void save(ImMsgBizUserHistory imMsgBizUserHistory) {
        imMsgBizUserHistoryMapper.save(imMsgBizUserHistory);
    }

    @Override
    public void update(ImMsgBizUserHistory imMsgBizUserHistory) {
        imMsgBizUserHistoryMapper.update(imMsgBizUserHistory);
    }

    @Override
    public void updateBatch(List<ImMsgBizUserHistory> imMsgBizUserHistories) {
        imMsgBizUserHistoryMapper.updateBatch(imMsgBizUserHistories);
    }

    @Override
    public void deleteById(Long id) {
        imMsgBizUserHistoryMapper.deleteById(id);
    }

    @Override
    public int countByUserUnread(Long imMsgBizUserId, Integer userUnread, Integer whoSend) {
        return imMsgBizUserHistoryMapper.countByUserUnread(imMsgBizUserId, userUnread, whoSend);
    }

    @Override
    public int countByEmployeeUnread(Long imMsgBizUserId, Integer employeeUnread, Integer whoSend) {
        return imMsgBizUserHistoryMapper.countByEmployeeUnread(imMsgBizUserId, employeeUnread, whoSend);
    }

    @Override
    public int countByEmployeeUnread2(Long imMsgBizUserId, Long employeeId, Integer employeeUnread, Integer whoSend) {
        return imMsgBizUserHistoryMapper.countByEmployeeUnread2(imMsgBizUserId, employeeId, employeeUnread, whoSend);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public ImMsgBizUserHistory saveHistory(Integer sendType, Long bizId, Long userId, Long employeeId, Integer type, String content, Integer whoSend) {
        ImMsgBizUser imMsgBizUser = imMsgBizUserService.getBySendTypeBizIdUserId(sendType, bizId, userId);
        if (Objects.isNull(imMsgBizUser)) {
            imMsgBizUser = new ImMsgBizUser();
            imMsgBizUser.setSendType(sendType);
            imMsgBizUser.setBizId(bizId);
            imMsgBizUser.setUserId(userId);
            imMsgBizUser.setBizUnreadNum(0);
            imMsgBizUser.setUserUnreadNum(0);
            imMsgBizUser.setCreateTime(new Date());
            imMsgBizUser.setUpdateTime(new Date());
            imMsgBizUserService.save(imMsgBizUser);
        }
        ImMsgBizUserHistory imMsgBizUserHistory = new ImMsgBizUserHistory();
        imMsgBizUserHistory.setImMsgBizUserId(imMsgBizUser.getId());
        imMsgBizUserHistory.setSendType(sendType);
        imMsgBizUserHistory.setBizId(bizId);
        imMsgBizUserHistory.setUserId(userId);
        imMsgBizUserHistory.setEmployeeId(employeeId);
        imMsgBizUserHistory.setType(type);
        imMsgBizUserHistory.setContent(content);
        imMsgBizUserHistory.setWhoSend(whoSend);
        if (Objects.equals(whoSend, WhoSend.EMPLOYEE)) {
            imMsgBizUserHistory.setUserUnread(MsgRead.UNREAD);
            imMsgBizUserHistory.setEmployeeUnread(MsgRead.READ);
        } else if (Objects.equals(whoSend, WhoSend.USER)) {
            imMsgBizUserHistory.setUserUnread(MsgRead.READ);
            imMsgBizUserHistory.setEmployeeUnread(MsgRead.UNREAD);
        }
        imMsgBizUserHistory.setCreateTime(new Date());
        imMsgBizUserHistory.setUpdateTime(new Date());
        imMsgBizUserHistory.setReadRange(0);
        this.save(imMsgBizUserHistory);
        return imMsgBizUserHistory;
    }

    @Override
    public MsgItemVO getUserPlatformMsgItem(UserApiVO user, ImMsgBizUserHistory imMsgBizUserHistory) {
        MsgItemVO msgItem = new MsgItemVO();
        msgItem.setChatType(imMsgBizUserHistory.getSendType());
        msgItem.setUserId(user.getUserId());
        msgItem.setUserHeadUrl(user.getPic());
        msgItem.setUserName(user.getNickName());
        msgItem.setNickName(imMsgBizUserHistory.getNickName());
        msgItem.setShopId(imMsgBizUserHistory.getBizId());
        msgItem.setShopName(imMsgBizUserHistory.getNickName());
        msgItem.setItemId(imMsgBizUserHistory.getId());
        msgItem.setEmployeeId(imMsgBizUserHistory.getEmployeeId());
        // todo 东8区，不应该写死"+8"后续优化
        msgItem.setTimestamp(imMsgBizUserHistory.getCreateTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime().toInstant(ZoneOffset.of("+8")).toEpochMilli());
        msgItem.setTimeStr(DateUtil.format(imMsgBizUserHistory.getCreateTime(), "yyyy/MM/dd HH:mm"));
        msgItem.setContent(imMsgBizUserHistory.getContent());
        msgItem.setType(imMsgBizUserHistory.getType());
        msgItem.setSource(imMsgBizUserHistory.getWhoSend());
        msgItem.setUserUnread(imMsgBizUserHistory.getUserUnread());
        msgItem.setEmployeeUnread(imMsgBizUserHistory.getEmployeeUnread());
        msgItem.setCreateTime(imMsgBizUserHistory.getCreateTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());
        msgItem.setUpdateTime(imMsgBizUserHistory.getUpdateTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());
        return msgItem;
    }

    @Override
    public MsgItemVO getUserShopMsgItem(EsShopDetailBO shopDetail, UserApiVO user, ImMsgBizUserHistory imMsgBizUserHistory) {
        MsgItemVO msgItem = new MsgItemVO();
        msgItem.setChatType(imMsgBizUserHistory.getSendType());
        msgItem.setUserId(user.getUserId());
        msgItem.setUserHeadUrl(user.getPic());
        msgItem.setUserName(user.getNickName());
        msgItem.setNickName(imMsgBizUserHistory.getNickName());
        msgItem.setShopLogo(shopDetail.getShopLogo());
        msgItem.setShopId(shopDetail.getShopId());
        msgItem.setShopName(shopDetail.getShopName());
        msgItem.setItemId(imMsgBizUserHistory.getId());
        msgItem.setEmployeeId(imMsgBizUserHistory.getEmployeeId());
        // todo 东8区，不应该写死"+8"后续优化
        msgItem.setTimestamp(imMsgBizUserHistory.getCreateTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime().toInstant(ZoneOffset.of("+8")).toEpochMilli());
        msgItem.setTimeStr(DateUtil.format(imMsgBizUserHistory.getCreateTime(), "yyyy/MM/dd HH:mm"));
        msgItem.setContent(imMsgBizUserHistory.getContent());
        msgItem.setType(imMsgBizUserHistory.getType());
        msgItem.setSource(imMsgBizUserHistory.getWhoSend());
        msgItem.setUserUnread(imMsgBizUserHistory.getUserUnread());
        msgItem.setEmployeeUnread(imMsgBizUserHistory.getEmployeeUnread());
        msgItem.setCreateTime(imMsgBizUserHistory.getCreateTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());
        msgItem.setUpdateTime(imMsgBizUserHistory.getUpdateTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());

        return msgItem;
    }

    @Override
    public PageVO<MsgItemVO> getUserPlatformHistory(SysUserVO sysUser, MessageInfoVO messageInfo, Long bizId, Long userId, UserApiVO user) {
        PageDTO pageDTO = new PageDTO();
        if (Objects.nonNull(messageInfo.getCurrent()) && Objects.nonNull(messageInfo.getSize())) {
            pageDTO.setPageNum(messageInfo.getCurrent());
            pageDTO.setPageSize(messageInfo.getSize());
        }
        PageVO<ImMsgBizUserHistory> history = this.pageBySendTypeBizIdUserId(pageDTO, messageInfo.getSendType(), bizId, null, userId);
        List<ImMsgBizUserHistory> imMsgBizUserHistories = history.getList();

        List<MsgItemVO> msgItems = new ArrayList<>();
        for (ImMsgBizUserHistory imMsgBizUserHistory : imMsgBizUserHistories) {
            MsgItemVO msgItem = this.getUserPlatformMsgItem(user, imMsgBizUserHistory);
            msgItems.add(msgItem);
        }
        PageVO<MsgItemVO> msgItemPage = new PageVO<>();
        BeanUtils.copyProperties(history, msgItemPage);
        msgItemPage.setList(msgItems);
        return msgItemPage;
    }

    @Override
    public PageVO<MsgItemVO> getUserShopHistory(EsShopDetailBO shopDetail, MessageInfoVO messageInfo, Long bizId, Long userId, UserApiVO user) {
        PageDTO pageDTO = new PageDTO();
        if (Objects.nonNull(messageInfo.getCurrent()) && Objects.nonNull(messageInfo.getSize())) {
            pageDTO.setPageNum(messageInfo.getCurrent());
            pageDTO.setPageSize(messageInfo.getSize());
        }
        PageVO<ImMsgBizUserHistory> history = this.pageBySendTypeBizIdUserId(pageDTO, messageInfo.getSendType(), bizId, null, userId);
        List<ImMsgBizUserHistory> imMsgBizUserHistories = history.getList();
        List<MsgItemVO> msgItems = new ArrayList<>();
        for (ImMsgBizUserHistory imMsgBizUserHistory : imMsgBizUserHistories) {
            MsgItemVO msgItem = this.getUserShopMsgItem(shopDetail, user, imMsgBizUserHistory);
            msgItems.add(msgItem);
        }
        PageVO<MsgItemVO> msgItemPage = new PageVO<>();
        BeanUtils.copyProperties(history, msgItemPage);
        msgItemPage.setList(msgItems);
        return msgItemPage;
    }

    @Override
    public PageVO<MsgItemVO> getShopUserHistory(UserInfoInTokenBO userInfoInToken, MessageInfoVO messageInfo, UserApiVO user, EsShopDetailBO shopDetail) {
        PageDTO pageDTO = new PageDTO();
        if (Objects.nonNull(messageInfo.getCurrent()) && Objects.nonNull(messageInfo.getSize())) {
            pageDTO.setPageNum(messageInfo.getCurrent());
            pageDTO.setPageSize(messageInfo.getSize());
        }
        PageVO<ImMsgBizUserHistory> history = this.pageBySendTypeBizIdUserId(pageDTO, SendType.SHOP, userInfoInToken.getTenantId(), userInfoInToken.getUserId(), user.getUserId());
        List<ImMsgBizUserHistory> imMsgBizUserHistories = history.getList();
        // 获取转接前的聊天记录(当天转接的记录+当前用户是自己负责才进行查询)
        getTransferHistory(userInfoInToken, user, SendType.SHOP, imMsgBizUserHistories);
        imMsgBizUserHistories.sort(Comparator.comparing(ImMsgBizUserHistory::getId, Comparator.reverseOrder()));
        List<MsgItemVO> msgItems = new ArrayList<>();
        for (ImMsgBizUserHistory imMsgBizUserHistory : imMsgBizUserHistories) {
            MsgItemVO msgItem = this.getUserShopMsgItem(shopDetail, user, imMsgBizUserHistory);
            msgItems.add(msgItem);
        }
        PageVO<MsgItemVO> msgItemPage = new PageVO<>();
        BeanUtils.copyProperties(history, msgItemPage);
        msgItemPage.setList(msgItems);
        return msgItemPage;
    }

    private void getTransferHistory(UserInfoInTokenBO userInfoInToken, UserApiVO user, Integer sendType, List<ImMsgBizUserHistory> imMsgBizUserHistories) {
        for (ImMsgBizUserHistory imMsgBizUserHistory : imMsgBizUserHistories) {
            //if (DateUtil.isSameDay(new Date(), imMsgBizUserHistory.getCreateTime()) && imMsgBizUserHistory.getContent().startsWith("系统：转接成功：")) {
            ImMsgBizUser imMsgBizUser = imMsgBizUserService.getBySendTypeBizIdUserId(sendType, userInfoInToken.getTenantId(), user.getUserId());
            // 当前用户是自己负责才进行查询
            if (Objects.equals(imMsgBizUser.getEmployeeId(), userInfoInToken.getUserId())) {
                //imMsgBizUserHistories.addAll(imMsgBizUserHistoryMapper.getHistoryBeforeTransfer(sendType, userInfoInToken.getTenantId(), userInfoInToken.getUserId(), user.getUserId()));
                // 获取平台和改用户所有的聊天记录以及最近一次转接成功的记录
                List<ImMsgBizUserHistory> imMsgBizUserHistoryList = imMsgBizUserHistoryMapper.getHistoryByUserId(sendType, userInfoInToken.getTenantId(), user.getUserId());
                imMsgBizUserHistories.clear();
                int temp = 0;
                for (ImMsgBizUserHistory msgBizUserHistory : imMsgBizUserHistoryList) {
                    if (msgBizUserHistory.getContent().contains("系统：转接成功：")) {
                        if (0 == temp) {
                            imMsgBizUserHistories.add(msgBizUserHistory);
                            temp = 1;
                        }
                        continue;
                    }
                    imMsgBizUserHistories.add(msgBizUserHistory);
                }
            }
            break;
            //}
        }
    }

    @Override
    public PageVO<MsgItemVO> getPlatformUserHistory(UserInfoInTokenBO userInfoInToken, MessageInfoVO messageInfo, UserApiVO user, SysUserVO sysUser) {
        PageDTO pageDTO = new PageDTO();
        if (Objects.nonNull(messageInfo.getCurrent()) && Objects.nonNull(messageInfo.getSize())) {
            pageDTO.setPageNum(messageInfo.getCurrent());
            pageDTO.setPageSize(messageInfo.getSize());
        }
        PageVO<ImMsgBizUserHistory> history = this.pageBySendTypeBizIdUserId(pageDTO, SendType.PLATFORM, Admin.ID, userInfoInToken.getUserId(), user.getUserId());
        List<ImMsgBizUserHistory> imMsgBizUserHistories = history.getList();
        getTransferHistory(userInfoInToken, user, SendType.PLATFORM, imMsgBizUserHistories);
        imMsgBizUserHistories.sort(Comparator.comparing(ImMsgBizUserHistory::getId, Comparator.reverseOrder()));
        // 获取消息历史包含的用户昵称
        List<MsgItemVO> msgItems = new ArrayList<>();
        for (ImMsgBizUserHistory imMsgBizUserHistory : imMsgBizUserHistories) {
            MsgItemVO msgItem = this.getUserPlatformMsgItem(user, imMsgBizUserHistory);
            msgItems.add(msgItem);
        }
        PageVO<MsgItemVO> msgItemPage = new PageVO<>();
        BeanUtils.copyProperties(history, msgItemPage);
        msgItemPage.setList(msgItems);
        return msgItemPage;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public List<ImMsgBizUserHistory> markUserPlatformRead(MessageInfoVO messageInfo, Long bizId, Long userId) {
        ImMsgBizUser imMsgBizUser = imMsgBizUserService.getBySendTypeBizIdUserId(SendType.PLATFORM, Admin.ID, userId);
        List<ImMsgBizUserHistory> imMsgBizUserHistories = new ArrayList<>();
        for (Long msgId : messageInfo.getMsgIds()) {
            ImMsgBizUserHistory imMsgBizUserHistory = this.getById(msgId);
            if (Objects.nonNull(imMsgBizUserHistory)) {
                if (Objects.equals(imMsgBizUserHistory.getImMsgBizUserId(), imMsgBizUser.getId()) && Objects.equals(imMsgBizUserHistory.getWhoSend(), WhoSend.EMPLOYEE)) {
                    if (Objects.equals(imMsgBizUserHistory.getUserUnread(), MsgRead.UNREAD)) {
                        imMsgBizUserHistory.setUserUnread(MsgRead.READ);
                        imMsgBizUserHistories.add(imMsgBizUserHistory);
                    }
                }
            }
        }
        if (!imMsgBizUserHistories.isEmpty()) {
            this.updateBatch(imMsgBizUserHistories);
            Integer userUnreadNum = this.countByUserUnread(imMsgBizUser.getId(), MsgRead.UNREAD, WhoSend.EMPLOYEE);
            imMsgBizUser.setUserUnreadNum(userUnreadNum);
            imMsgBizUserService.update(imMsgBizUser);
        }
        return imMsgBizUserHistories;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public List<ImMsgBizUserHistory> markUserShopRead(MessageInfoVO messageInfo, Long bizId, Long userId) {
        ImMsgBizUser imMsgBizUser = imMsgBizUserService.getBySendTypeBizIdUserId(SendType.SHOP, bizId, userId);
        List<ImMsgBizUserHistory> imMsgBizUserHistories = new ArrayList<>();
        for (Long msgId : messageInfo.getMsgIds()) {
            ImMsgBizUserHistory imMsgBizUserHistory = this.getById(msgId);
            if (Objects.nonNull(imMsgBizUserHistory)) {
                if (Objects.equals(imMsgBizUserHistory.getImMsgBizUserId(), imMsgBizUser.getId()) && Objects.equals(imMsgBizUserHistory.getWhoSend(), WhoSend.EMPLOYEE)) {
                    if (Objects.equals(imMsgBizUserHistory.getUserUnread(), MsgRead.UNREAD)) {
                        imMsgBizUserHistory.setUserUnread(MsgRead.READ);
                        imMsgBizUserHistories.add(imMsgBizUserHistory);
                    }
                }
            }
        }
        if (!imMsgBizUserHistories.isEmpty()) {
            this.updateBatch(imMsgBizUserHistories);
            Integer userUnreadNum = this.countByUserUnread(imMsgBizUser.getId(), MsgRead.UNREAD, WhoSend.EMPLOYEE);
            imMsgBizUser.setUserUnreadNum(userUnreadNum);
            imMsgBizUserService.update(imMsgBizUser);
        }
        return imMsgBizUserHistories;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public List<ImMsgBizUserHistory> markShopUserRead(MessageInfoVO messageInfo, UserInfoInTokenBO userInfoInToken, Long userId) {
        ImMsgBizUser imMsgBizUser = imMsgBizUserService.getBySendTypeBizIdUserId(SendType.SHOP, userInfoInToken.getTenantId(), userId);
        List<ImMsgBizUserHistory> imMsgBizUserHistories = new ArrayList<>();
        for (Long msgId : messageInfo.getMsgIds()) {
            ImMsgBizUserHistory imMsgBizUserHistory = this.getById(msgId);
            if (Objects.nonNull(imMsgBizUserHistory)) {
                if (Objects.equals(imMsgBizUserHistory.getImMsgBizUserId(), imMsgBizUser.getId()) && Objects.equals(imMsgBizUserHistory.getWhoSend(), WhoSend.USER)) {
                    if (Objects.equals(imMsgBizUserHistory.getEmployeeUnread(), MsgRead.UNREAD)) {
                        imMsgBizUserHistory.setEmployeeUnread(MsgRead.READ);
                        imMsgBizUserHistories.add(imMsgBizUserHistory);
                    }
                }
            }
        }
        if (!imMsgBizUserHistories.isEmpty()) {
            this.updateBatch(imMsgBizUserHistories);
            // 更新店铺未读条数
            Integer bizUnreadNum = this.countByEmployeeUnread(imMsgBizUser.getId(), MsgRead.UNREAD, WhoSend.USER);
            imMsgBizUser.setBizUnreadNum(bizUnreadNum);
            imMsgBizUserService.update(imMsgBizUser);
            // 更新客服未读条数
            ImMsgBizEmployeeRecent imMsgBizEmployeeRecent = imMsgBizEmployeeRecentService.getBySendTypeBizIdEmployeeIdUserId(SendType.SHOP, userInfoInToken.getTenantId(), userInfoInToken.getUserId(), userId);
            Integer employeeUnreadNum = this.countByEmployeeUnread2(imMsgBizUser.getId(), userInfoInToken.getUserId(), MsgRead.UNREAD, WhoSend.USER);
            imMsgBizEmployeeRecent.setEmployeeUnreadNum(employeeUnreadNum);
            imMsgBizEmployeeRecentService.update(imMsgBizEmployeeRecent);
        }
        return imMsgBizUserHistories;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public List<ImMsgBizUserHistory> markPlatformUserRead(MessageInfoVO messageInfo, UserInfoInTokenBO userInfoInToken, Long userId) {
        ImMsgBizUser imMsgBizUser = imMsgBizUserService.getBySendTypeBizIdUserId(SendType.PLATFORM, Admin.ID, userId);
        List<ImMsgBizUserHistory> imMsgBizUserHistories = new ArrayList<>();
        for (Long msgId : messageInfo.getMsgIds()) {
            ImMsgBizUserHistory imMsgBizUserHistory = this.getById(msgId);
            if (Objects.nonNull(imMsgBizUserHistory)) {
                if (Objects.equals(imMsgBizUserHistory.getImMsgBizUserId(), imMsgBizUser.getId()) && Objects.equals(imMsgBizUserHistory.getWhoSend(), WhoSend.USER)) {
                    if (Objects.equals(imMsgBizUserHistory.getEmployeeUnread(), MsgRead.UNREAD)) {
                        imMsgBizUserHistory.setEmployeeUnread(MsgRead.READ);
                        imMsgBizUserHistories.add(imMsgBizUserHistory);
                    }
                }
            }
        }
        if (!imMsgBizUserHistories.isEmpty()) {
            this.updateBatch(imMsgBizUserHistories);
            Integer bizUnreadNum = this.countByEmployeeUnread(imMsgBizUser.getId(), MsgRead.UNREAD, WhoSend.USER);
            imMsgBizUser.setBizUnreadNum(bizUnreadNum);
            imMsgBizUserService.update(imMsgBizUser);
            // 更新客服未读条数
            ImMsgBizEmployeeRecent imMsgBizEmployeeRecent = imMsgBizEmployeeRecentService.getBySendTypeBizIdEmployeeIdUserId(SendType.PLATFORM, userInfoInToken.getTenantId(), userInfoInToken.getUserId(), userId);
            Integer employeeUnreadNum = this.countByEmployeeUnread2(imMsgBizUser.getId(), userInfoInToken.getUserId(), MsgRead.UNREAD, WhoSend.USER);
            imMsgBizEmployeeRecent.setEmployeeUnreadNum(employeeUnreadNum);
            imMsgBizEmployeeRecentService.update(imMsgBizEmployeeRecent);
        }
        return imMsgBizUserHistories;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public ImMsgBizUserHistory saveUserPlatformHistory(MessageInfoVO messageInfo, Long bizId, Long userId, Long employeeId) {
        ImMsgBizUserHistory imMsgBizUserHistory = this.saveHistory(messageInfo.getSendType(), bizId, userId, employeeId, messageInfo.getMsgType(), messageInfo.getContent(), WhoSend.USER);
        imMsgBizUserService.updateBizUserLastMsg(imMsgBizUserHistory);
        imMsgBizEmployeeRecentService.updateEmployeeRecent(imMsgBizUserHistory);
        return imMsgBizUserHistory;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public ImMsgBizUserHistory saveUserShopHistory(MessageInfoVO messageInfo, Long bizId, Long userId, Long employeeId) {
        ImMsgBizUserHistory imMsgBizUserHistory = this.saveHistory(messageInfo.getSendType(), bizId, userId, employeeId, messageInfo.getMsgType(), messageInfo.getContent(), WhoSend.USER);
        imMsgBizUserService.updateBizUserLastMsg(imMsgBizUserHistory);
        imMsgBizEmployeeRecentService.updateEmployeeRecent(imMsgBizUserHistory);
        return imMsgBizUserHistory;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public ImMsgBizUserHistory saveShopUserHistory(MessageInfoVO messageInfo, UserInfoInTokenBO userInfoInToken) {
        ImMsgBizUserHistory imMsgBizUserHistory = this.saveHistory(SendType.SHOP, userInfoInToken.getTenantId(), messageInfo.getToId(), userInfoInToken.getUserId(), messageInfo.getMsgType(), messageInfo.getContent(), WhoSend.EMPLOYEE);
        imMsgBizUserService.updateBizUserLastMsg(imMsgBizUserHistory);
        imMsgBizEmployeeRecentService.updateEmployeeRecent(imMsgBizUserHistory);
        return imMsgBizUserHistory;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public ImMsgBizUserHistory savePlatformUserHistory(MessageInfoVO messageInfo, UserInfoInTokenBO userInfoInToken) {
        ImMsgBizUserHistory imMsgBizUserHistory = this.saveHistory(SendType.PLATFORM, Admin.ID, messageInfo.getToId(), userInfoInToken.getUserId(), messageInfo.getMsgType(), messageInfo.getContent(), WhoSend.EMPLOYEE);
        imMsgBizUserService.updateBizUserLastMsg(imMsgBizUserHistory);
        imMsgBizEmployeeRecentService.updateEmployeeRecent(imMsgBizUserHistory);
        return imMsgBizUserHistory;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public ImMsgBizUserHistory saveShopChangeEmployeeReply(UserInfoInTokenBO userInfoInToken, ShopUserVO shopUserVO, UserApiVO user) {
        String content = "系统：转接成功：" + shopUserVO.getNickName() + "客服为您服务";
        ImMsgBizUserHistory imMsgBizUserHistory = this.saveHistory(SendType.SHOP, userInfoInToken.getTenantId(), user.getUserId(), shopUserVO.getShopUserId(), MsgType.TEXT, content, WhoSend.EMPLOYEE);
        // 多保存一份转接前客服的转接聊天记录
        imMsgBizUserHistory.setEmployeeId(userInfoInToken.getUserId());
        imMsgBizUserHistory.setReadRange(1);
        this.save(imMsgBizUserHistory);
        imMsgBizUserHistory.setEmployeeId(shopUserVO.getShopUserId());

        imMsgBizUserService.updateBizUserLastMsg(imMsgBizUserHistory);
        imMsgBizEmployeeRecentService.updateEmployeeRecent(imMsgBizUserHistory);
        return imMsgBizUserHistory;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public ImMsgBizUserHistory savePlatformChangeEmployeeReply(UserInfoInTokenBO userInfoInToken, SysUserVO sysUser3, UserApiVO user) {
        String content = "系统：转接成功：" + sysUser3.getNickName() + "客服为您服务";
        ImMsgBizUserHistory imMsgBizUserHistory = this.saveHistory(SendType.PLATFORM, Admin.ID, user.getUserId(), sysUser3.getSysUserId(), MsgType.TEXT, content, WhoSend.EMPLOYEE);
        // 多保存一份转接前客服的转接聊天记录
        imMsgBizUserHistory.setEmployeeId(userInfoInToken.getUserId());
        imMsgBizUserHistory.setReadRange(1);
        this.save(imMsgBizUserHistory);
        imMsgBizUserHistory.setEmployeeId(sysUser3.getSysUserId());

        imMsgBizUserService.updateBizUserLastMsg(imMsgBizUserHistory);
        imMsgBizEmployeeRecentService.updateEmployeeRecent(imMsgBizUserHistory);
        return imMsgBizUserHistory;
    }
}
